/*
 *  Copyright 2010 Alexey Frishman (alexey.frishman@gmail.com)
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not
 *  use this file except in compliance with the License. You may obtain a copy of
 *  the License at
 *  
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations under
 *  the License.
 * 
 */

package org.json4g.serialization.policy.jaxb;

import static org.json4g.TypeUtil.getClassType;

import javax.xml.bind.annotation.XmlElement;

import org.json4g.serialization.policy.GenericTypeExtractor;

import com.gwtent.reflection.client.ClassType;
import com.gwtent.reflection.client.Field;

/**
 * Extracts generic type for field based on @XmlElement(type=...) attribute
 */
public class JaxbGenericTypeExtractor implements GenericTypeExtractor {

    @Override
    public ClassType extract(Field field) {
        XmlElement annotation = field.getAnnotation(XmlElement.class);
        
        if (annotation == null) {
            throw new IllegalStateException("Current serialization policy requires @XmlElement annotation on every serializable collection field,"
                    + " but it is missing on the field '" + field.getName() + "' " + " in " + field.getEnclosingType());
        }

        Class<?> annotationType = annotation.type();
        
        if (annotationType == null || annotationType == XmlElement.DEFAULT.class) { // TODO check and commit to SVN
            throw new IllegalStateException("Current serialization policy requires @XmlElement annotation on collection field"
                    + " to contain 'type' attribute, which identifies type of elements in the collection."
                    + " The annotation is present, but the 'type' attribute is missing on the field '"
                    + field.getName() + "' " + " in " + field.getEnclosingType());
        }
        
        ClassType result = getClassType(annotationType);

        return result;
    }

}
